package com.longbig.controller;

/**
 * @author: yyl
 * @date: 2025/4/10:15:37
 */

import com.longbig.converter.X6ToBpmnConverter;
import com.longbig.service.ProcessDeployService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/process")
@Slf4j
public class ProcessDeployController {

    @Autowired
    private ProcessDeployService processDeployService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private X6ToBpmnConverter x6ToBpmnConverter;

    @PostMapping("/deploy")
    public ResponseEntity<?> deployProcess(
            @RequestParam String processName,
            @RequestBody String x6JsonStr) {

        try {

            String bpmnXmlContent = x6ToBpmnConverter.buildTopology(x6JsonStr);
            String deploymentId = processDeployService.deployProcess(processName, bpmnXmlContent);
            String definitionId = processDeployService.getLatestProcessDefinitionId(processName, deploymentId);

            Map<String, String> response = new HashMap<>();
            response.put("deploymentId", deploymentId);
            response.put("processDefinitionId", definitionId);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("deployProcess error", e);
            return null;

        }
    }

    @PostMapping("/start")
    public String startProcess(
            @RequestParam String processDefinitionId) {

        runtimeService.startProcessInstanceById(processDefinitionId);
        return "流程实例已启动";
    }
}